<?php

session_start();


require_once '../common/config.php';
require_once '../common/conn.php';
require_once '../common/function.php';
require_once '../db/account.db.php';
require_once '../db/point.db.php';

$action = $_POST['action'];

switch ($action) {
    case 'addCart':
        $res = getJavaServerQrCodeUrl();
        break;
    case 'deleteCart':
        $res = deleteCart();
        break;
    case 'confirmBuy':
        $res = confirmBuy();
        break;
    default:
        $res['code'] = 2;
        $res['msg'] = '申请类型错误';
}

echo json_encode($res);



/**
 * 添加到购物车
 */
function addCart() {
    $itemcode = isset($_POST['item_code']) ? addslashes(trim($_POST['item_code'])) : "";
    $array = array();
    if (isset($_SESSION['cart'])) {
        $array = $_SESSION['cart'];
    }
    array_push($array, $itemcode);

    $_SESSION['cart'] = $array;
    $res['code'] = 0;
    return $res;
}

/**
 * 删除购物车中的商品
 * @return int
 */
function deleteCart() {
    $itemcode = isset($_POST['item_code']) ? addslashes(trim($_POST['item_code'])) : "";

    $array = array();
    $newArray = array();
    if (isset($_SESSION['cart'])) {
        $array = $_SESSION['cart'];
        $newArray = $_SESSION['cart'];
    }
    for ($i = 0; $i < count($array); $i++) {
        if ($array[$i] == $itemcode) {
            unset($newArray[$i]);
        }
    }
    $array = array();
    $key = 0;
    foreach ($newArray as $value) {
        $array[$key] = $value;
        $key++;
    }
    $_SESSION['cart'] = $array;
    unset($newArray);

    $res['code'] = 0;
    return $res;
}

/**
 * 购买道具
 */
function confirmBuy() {
    $price = isset($_POST['price']) ? trim($_POST['price']) : "";
    $itemNo = isset($_POST['itemNo']) ? addslashes(trim($_POST['itemNo'])) : "";
    $id_x = isset($_POST['id_x']) ? addslashes(trim($_POST['id_x'])) : "";
    $buy = isset($_POST['buy']) ? addslashes(trim($_POST['buy'])) : "";
    $haoyou = isset($_POST['haoyou']) ? addslashes(trim($_POST['haoyou'])) : "";

//    file_put_contents("post.txt", json_encode($_POST));

    if (!is_numeric($price)) {
        $res['code'] = 3;
        $res['msg'] = "价格不是数字";
        return $res;
    }

    if ($buy == "false" && $haoyou == "") {
        $res['code'] = 4;
        $res['msg'] = "请选择好友";
        return $res;
    }

    $dbc = new DBC();
    $sql = "SELECT * FROM AccountMoney WHERE AccUnique = " . $_SESSION['AccUnique'];
    $data = $dbc->fetchData($sql);
    $sql = "SELECT * FROM item_buy_info WHERE accunique = '" . $_SESSION['AccUnique'] . "' AND account_id = '" . $_SESSION['AccountID'] . "' ORDER BY id_x DESC";
    $data_item_buy_infodata =$dbc->fetchData($sql);

    // file_put_contents("sql.txt", $sql . "\r\n", 8);

    if (isArrayNotEmpty($data) && (($data[0]['Balance'] < $price) || ($data[0]['Balance'] == 0))) {
        $res['code'] = 2;
        $res['msg'] = "余额不足";
        return $res;
    } else {
        $sqls = array();
        $sql = "UPDATE AccountMoney SET Balance = Balance - " . $price . " WHERE AccUnique = " . $_SESSION['AccUnique'];
        array_push($sqls, $sql);
//        file_put_contents("sql.txt", $sql . "\r\n", 8);

        $unionNo = date("YmdHis") . "_" . $_SESSION['AccUnique'];
        $num = 1;
        $sql = "INSERT INTO AccountMoneyDetail(AccUnique,ItemIdx,ItemCount,UpdateTime,ItemNo,UnionNo) "
            . "VALUES('" . $_SESSION['AccUnique'] . "','" . $id_x . "','" . $num . "',getDate(),'" . $itemNo . "','" . $unionNo . "')";
        array_push($sqls, $sql);
//        file_put_contents("sql.txt", $sql . "\r\n", 8);

        ///累积购买赠送部分// 20180820
        $lh_count = 0;
        $sqlSendhave = "select * from AccountSendItem where AccUnique = '" . $_SESSION['AccUnique'] . "'";
        $Ishavedata = $dbc->fetchData($sqlSendhave);
        if($itemNo == 268472410)
        {
            $lh_count = 1;
        }elseif($itemNo == 269390870)
        {
            $lh_count = 50;
        }elseif($itemNo == 269390871)
        {
            $lh_count = 100;
        }elseif($itemNo == 2684763981){
			$itemNo = 268476398;
			$num = 20;
		}elseif($itemNo == 2684763941){
			$itemNo = 268476394;
			$num = 20;
		}elseif($itemNo == 2684763951){
			$itemNo = 268476395;
			$num = 20;
		}elseif($itemNo == 2684764381){
			$itemNo = 268476438;
			$num = 250;
		}elseif($itemNo == 2684764391){
			$itemNo = 268476439;
			$num = 250;
		}elseif($itemNo == 2684764401){
			$itemNo = 268476440;
			$num = 250;
		}
        if($lh_count > 0)
        {
            if(!isArrayNotEmpty($Ishavedata))
            {
                $sql = "INSERT INTO AccountSendItem(AccUnique,UpdateTime,Stauts,AllCount) "
                    . "VALUES('" . $_SESSION['AccUnique'] . "',getDate(),0,'" . $lh_count . "')";

                //file_put_contents("sql.txt", $sql . "\r\n", 8);
            }else
            {
                $sql = "update AccountSendItem set AllCount = AllCount + '" . $lh_count . "' where AccUnique = '" . $_SESSION['AccUnique'] . "'";
            }
            array_push($sqls, $sql);//加入sql到数组
        }



/////////////////////////


        if ($buy == "true") {

			// 买材料2500个再发9次
			if($itemNo == 2684764382){
				$itemNo = 268476438;
				$num = 250;
				
				$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','"
                . $itemNo . "','" . $num . "',3,getDate())";

				for($i = 0; $i < 10; $i++) {
					array_push($sqls, $sql);
				}
			}elseif($itemNo == 2684764392){
				$itemNo = 268476439;
				$num = 250;

				$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','"
                . $itemNo . "','" . $num . "',3,getDate())";

				for($i = 0; $i < 10; $i++) {
					array_push($sqls, $sql);
				}
			}elseif($itemNo == 2684764402){
				$itemNo = 268476440;
				$num = 250;

				$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','"
                . $itemNo . "','" . $num . "',3,getDate())";

				for($i = 0; $i < 10; $i++) {
					array_push($sqls, $sql);
				}
			}
			else
			{
				$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','"
                . $itemNo . "','" . $num . "',3,getDate())";

				array_push($sqls, $sql);
			}
            
            //补充日志
            $user_ip = $_SERVER["REMOTE_ADDR"];
            $sql = "insert into TAccount..item_buy_log(id_x,accunique,account_id,item_using,item_price,product_id,ItemIndex,Item_count,buy_dated,Ip_Address) values('" . $data_item_buy_infodata[0]['id_x'] . "','" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "',0,'". $price . "','" . $itemNo . " ','" . $itemNo . "','". $num . "',getdate(),'" . $user_ip . "')";
            array_push($sqls, $sql);
//            file_put_contents("sql.txt", $sql . "\r\n", 8);
        } else {
            $sql = "SELECT * FROM Account WHERE AccUnique = '" . $haoyou . "'";
            $data10 = $dbc->fetchData($sql);
//            file_put_contents("sql.txt", $sql . "\r\n", 8);
            if (count($data10) > 0) {

				// 买材料2500个再发9次
				if($itemNo == 2684764382){
					$itemNo = 268476438;
					$num = 250;
					
					$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                    . "VALUES('" . $haoyou . "','" . $data10[0]['AccountID'] . "','139','"
                    . $itemNo . "','" . $num . "',3,getDate())";

					for($i = 0; $i < 10; $i++) {
						array_push($sqls, $sql);
					}
				}elseif($itemNo == 2684764392){
					$itemNo = 268476439;
					$num = 250;

					$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                    . "VALUES('" . $haoyou . "','" . $data10[0]['AccountID'] . "','139','"
                    . $itemNo . "','" . $num . "',3,getDate())";

					for($i = 0; $i < 10; $i++) {
						array_push($sqls, $sql);
					}
				}elseif($itemNo == 2684764402){
					$itemNo = 268476440;
					$num = 250;

					$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                    . "VALUES('" . $haoyou . "','" . $data10[0]['AccountID'] . "','139','"
                    . $itemNo . "','" . $num . "',3,getDate())";

					for($i = 0; $i < 10; $i++) {
						array_push($sqls, $sql);
					}
				}
				else
				{
					$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                    . "VALUES('" . $haoyou . "','" . $data10[0]['AccountID'] . "','139','"
                    . $itemNo . "','" . $num . "',3,getDate())";

					array_push($sqls, $sql);

				}

                
                //补充赠送日志
				$sql = "INSERT INTO AccountSendOtherItem(AccUnique,TarAccUnique,ItemIndex, ItemCount,UpdateTime) "
                    . "VALUES('" . $_SESSION['AccUnique'] . "','" . $haoyou . "','" . $itemNo . "', '". $num . "', getDate())";
				array_push($sqls, $sql);

//                file_put_contents("sql.txt", $sql . "\r\n", 8);
            }
        }


        $result = $dbc->executeBatch($sqls);


        //////////////////////////////////////////
        //20180820 增加送深红逻辑//
        $SendNeedCount = 166;//购买多少个送
        $shid = 268476200;//深红ID
		$send11 = 269459419; //+11卷
        $sendcount = 2;//送几个
		$sendcount11 = 2;//+11 count
        $sqlAlreadyBuy = "select * from AccountSendItem where AccUnique = '" . $_SESSION['AccUnique'] . "'";
        $AlreadyBuyData = $dbc->fetchData($sqlAlreadyBuy);
        $AlreadyBuyCount = $AlreadyBuyData[0]['AllCount'];
        if( $AlreadyBuyCount >= $SendNeedCount)//这里满足就执行
        {
            $sqlp = array();
            $sql = "update AccountSendItem set AllCount = AllCount - '" . $SendNeedCount . "' where AccUnique = '" . $_SESSION['AccUnique'] . "'";
            array_push($sqlp, $sql);
            $sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" .  $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','" . $shid . "','" . $sendcount . "',3,getDate())";
            array_push($sqlp,$sql);
			$sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" .  $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','" . $send11 . "','" . $sendcount11 . "',3,getDate())";
            array_push($sqlp,$sql);
            $sql = "INSERT INTO SendItemLog(SendAcc,SendAccID,SendItemId,SendTime,SendCount) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','". $shid . "',getDate(),'" .$sendcount . "')";
            //$dbc->execute($sql);//这里满足就执行
            array_push($sqlp,$sql);
			$sql = "INSERT INTO SendItemLog(SendAcc,SendAccID,SendItemId,SendTime,SendCount) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','". $send11 . "',getDate(),'" .$sendcount11 . "')";
            //$dbc->execute($sql);//这里满足就执行
            array_push($sqlp,$sql);
            $dbc->executeBatch($sqlp);
        }





        $dbc->close();

        if ($result) {
            //////////////////////////////////////////////////
            /*
             * //消费送积分逻辑 20181129 增加
             */
            $min_need_balance = 5;
            $payDB = "payment_db";
            if( $price > $min_need_balance )
            {
                $sendpoint = floor($price/$min_need_balance);//本次要发送的积分
                $dbc2 = new DBC($payDB);
                $paymentdb = new pointDB($dbc2);
                $Send_Point_Result = $paymentdb->StoreSendPoint($_SESSION['AccUnique'],$_SESSION['AccountID'],$sendpoint,2);
                $res['Send_Code'] = $Send_Point_Result['code'];
                $res['Send_Msg'] = $Send_Point_Result['msg'];
                $res['sendpoint'] = $sendpoint;
            }else{
                $res['Send_Code'] = 1;
                $res['Send_Msg'] = "本次消费不满足获赠积分";
            }
            /////////////////////////////////////////////
            $balance = $data[0]['Balance'] - $price;
            $res['code'] = 0;
            $res['msg'] = "";
            $res['balance'] = $balance;

        } else {
            $res['code'] = 1;
            $res['msg'] = "失败";
        }
        $dbc2->close();
        return $res;
    }
}
